#include <test.hpp>
using namespace cv;
using namespace std;
void my_mouse_callback( int event, int x, int y, int flags, void* param ){
    Mat* image = (Mat*) param;
//    cvtColor(*image,*image,CV_BGR2HSV);
    uchar *data = image->data;
    switch( event ){
    	case CV_EVENT_MOUSEMOVE: 
    		
    		break;

    	case CV_EVENT_LBUTTONDOWN:
        cout<<"X :"<<x<<" Y :"<<y<<endl;
    		break;

    	case CV_EVENT_LBUTTONUP:
    		
    		break;
	}
}
int main()
{
    Mat image = imread("threshold_image.png",0);
    Mat image2= Mat::zeros(image.rows, image.cols, CV_8UC3);
    vector<vector<Point> > vecContours;
    vector<Vec4i> vech1,vech2;
    vector<Point> center;
    findContours(image,vecContours,vech1,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
    if (vech1 != vech2)
    {
        // iterate through all the top-level contours,
        for(int idx = 0; idx >= 0; idx = vech1[idx][0] )
        { 
            // draw each connected component with its own FIXED color
            Scalar color( 255, 0,0 );
            drawContours( image2, vecContours, idx, color, /*1*/ CV_FILLED, 8, vech1 );
            //cout << vecContours[idx][0] << " - - " << sColor[idx] << " - - Index: " << idx << endl;
           
        }
    }
    for(int i=0;i<vecContours.size();i++)
    {
        int x=0;
        int y=0;
        for(int j=0;j<vecContours[i].size();j++)
        {
           x+= ((vecContours[i])[j]).x;
           y+= ((vecContours[i])[j]).y;
            //cout<<"contour "<<i<<" points "<<((vecContours[i])[j]).x<<" "<<((vecContours[i])[j]).y<<" "<<endl;
        }
        center.push_back(Point(x/vecContours[i].size(),y/vecContours[i].size()));
    }
    for(int i=0;i<vecContours.size();i++)
    {
        int k;
        for(int j=i;j<vecContours.size();j++)
        {
            
            if(((abs(center[i].x-center[j].x))<10)&&((abs(center[i].y-center[j].y)>35))&&((abs(center[i].y-center[j].y))<70))
             {
                 cout<<"contour "<<i<<"with "<<j<<" "<<endl;
                 Scalar color( 0, 255,0 );
                 drawContours( image2, vecContours,i, color, /*1*/ CV_FILLED, 8, vech1 );
                 drawContours( image2, vecContours,j, color, /*1*/ CV_FILLED, 8, vech1 );
             }
        }
        //cout<<"contour "<<i<<"centre"<<(center[i]).x<<" "<<(center[i]).y<<" "<<endl;
    }
    imshow("input",image);
    waitKey(0);
    imshow("output",image2);
    cvSetMouseCallback( "output", my_mouse_callback,(void *)&image2);
    waitKey(0);
    return 0;
}
